package gw.com.android.ui.home;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.List;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.HomePresenter;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.views.FloatAdverView;
import gw.com.android.ui.views.MyScrollView;
import gw.com.android.ui.views.NoticeView;
import gw.com.android.ui.views.banner.Banner;
import gw.com.android.ui.views.banner.BannerConfig;
import gw.com.android.ui.views.banner.listener.OnBannerListener;
import gw.com.android.utils.BannerImageLoader;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.util.DeviceUtil;
import www.com.library.view.PullDownElasticImp;
import www.com.library.view.PullDownScrollView;
import www.com.library.view.ScrollPoints;

/**
 * FT 1.1 新首页
 * <p>
 * 保留原有banner图，自选行情，开户。其他都剪除
 * <p>
 * 另，新增 新手福利广告，新手指南，关于恒信
 * <p>
 * 另，把要闻，快讯，日历三合一Fragment，直接放到首页
 */
public class HomeFragment extends PushMsgTabFragment implements PullDownScrollView.RefreshListener, View.OnClickListener {

    private PullDownScrollView mPullDownScrollView;
    private MyScrollView mScrollView;
    private FrameLayout mHeadBar;
    //头部轮播广告
    private Banner mBanner;
    //自选行情相关
    private ViewPager mProductPager;
    private ScrollPoints mProductPoint;
    //开户广告
    private TextView tvOpenRealDesc, tvOpenDemoDesc;
    //新手福利
    private HomeWelfareView mWelfareView;
    //新手指南+关于恒信
    private ImageView ivNewbie, ivAboutUs;
    //要闻、快讯、日历等资讯
    private SlidingTabLayout mNewsTab;
    private ViewPager mNewsPager;
    //跑马灯
    private NoticeView noticeView;
    // 首页的浮动广告
    private FloatAdverView mFloatAdView;

    private ProductPagerAdapter mProductAdapter;
    private NewsPageAdapter mNewsAdapter;
    private HomePresenter homePresenter;
    private boolean wholeNewsMode = false; //首页是否进入显示资讯的模式

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_home;
    }

    @Override
    protected void initLayoutView() {
        mPullDownScrollView = mRootView.findViewById(R.id.home_pull_down_scroll_view);
        mScrollView = mRootView.findViewById(R.id.home_scroll_view);
        mHeadBar = mRootView.findViewById(R.id.home_title_bar);
        mHeadBar.findViewById(R.id.home_service).setOnClickListener(this);
        mBanner = mRootView.findViewById(R.id.home_banner);
        //products
        mProductPager = mRootView.findViewById(R.id.home_product_pager);
        mProductPoint = mRootView.findViewById(R.id.home_product_point);
        //open account
        View viewOpenAccount = mRootView.findViewById(R.id.home_open_account);
        View viewOpenDemo = mRootView.findViewById(R.id.home_open_account_demo);
        View viewOpenReal = mRootView.findViewById(R.id.home_open_account_real);
        tvOpenRealDesc = mRootView.findViewById(R.id.home_open_account_real_desc);
        tvOpenDemoDesc = mRootView.findViewById(R.id.home_open_account_demo_desc);
        // welfare ad view
        mWelfareView = mRootView.findViewById(R.id.home_new_welfare);
        // newbie guide ad  and about us ad
        ivNewbie = mRootView.findViewById(R.id.home_newbie_guide);
        ivAboutUs = mRootView.findViewById(R.id.home_about_us);
        // topnews  flash calendar
        mNewsTab = mRootView.findViewById(R.id.home_news_tab);
        mNewsPager = mRootView.findViewById(R.id.home_news_pager);

        noticeView = mRootView.findViewById(R.id.home_notice);
        mFloatAdView = mRootView.findViewById(R.id.home_float_ad);
        // 开户栏
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            viewOpenAccount.setVisibility(View.VISIBLE);
            viewOpenDemo.setOnClickListener(this);
            viewOpenReal.setOnClickListener(this);
            resizeOpenAccount(viewOpenDemo, viewOpenReal);
        } else {
            viewOpenAccount.setVisibility(View.GONE);
        }
        mScrollView.setScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int top, int distance) {
                scroll(top, distance);
            }
        });
        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mRootView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                // 计算资讯pager的高度，正好能占满屏，完美！
                final View viewPoint = mRootView.findViewById(R.id.home_base_line);
                int pagerHeight = (int) (viewPoint.getY() - mHeadBar.getY() - mNewsTab.getHeight() + 2);
                ViewGroup.LayoutParams params = mNewsPager.getLayoutParams();
                params.height = pagerHeight;
                mNewsPager.setLayoutParams(params);
            }
        });

        homePresenter = new HomePresenter(getActivity());
        mPullDownScrollView.setRefreshListener(this);
        int edge = DeviceUtil.instance().dip2px(3, getContext());
        mProductPoint.setPointWidthHeight(edge, edge);
        resizeNewbieAbout(ivNewbie, ivAboutUs);

        PullDownElasticImp elasticImp = new PullDownElasticImp(getContext());
        elasticImp.getElasticLayout().setTranslationY(DeviceUtil.instance().dip2px(40, getContext()));
        mPullDownScrollView.setPullDownElastic(elasticImp);
    }

    /**
     * 宽高比例为：540*210
     */
    private void resizeOpenAccount(View demoView, View realView) {
        int screenWidth = DeviceUtil.instance().getScreenPixelsWidth(getActivity());
        if (screenWidth > 0) {
            int width = screenWidth / 2 - DeviceUtil.instance().dip2px(10, getContext());
            ViewGroup.LayoutParams demoParam = demoView.getLayoutParams();
            ViewGroup.LayoutParams realParam = realView.getLayoutParams();
            demoParam.height = realParam.height = (int) (210 * 1.0F / 540 * width);
            demoView.setLayoutParams(demoParam);
            realView.setLayoutParams(realParam);
        }
    }

    /**
     * 宽高比例为：528*270
     */
    private void resizeNewbieAbout(View newbieView, View aboutView) {
        int screenWidth = DeviceUtil.instance().getScreenPixelsWidth(getActivity());
        if (screenWidth > 0) {
            int width = screenWidth / 2 - DeviceUtil.instance().dip2px(10, getContext());
            ViewGroup.LayoutParams newbieParam = newbieView.getLayoutParams();
            ViewGroup.LayoutParams aboutParam = aboutView.getLayoutParams();
            newbieParam.height = aboutParam.height = (int) (270 * 1.0F / 528 * width);
            newbieView.setLayoutParams(newbieParam);
            aboutView.setLayoutParams(aboutParam);
        }
    }

    @Override
    protected void initViewData() {
        mProductAdapter = new ProductPagerAdapter(getActivity(), String.valueOf(GTSConst.ZONE_TYPE_SELF));
        mProductPager.setAdapter(mProductAdapter);
        mProductPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mProductPoint.changeSelectedPoint(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mNewsAdapter = new NewsPageAdapter(getActivity());
        mNewsPager.setAdapter(mNewsAdapter);
        mNewsPager.setOffscreenPageLimit(3);
        //mNewsTab.setupWithViewPager(mNewsPager);
        mNewsTab.setViewPager(mNewsPager);
        mNewsPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mNewsAdapter.onPageSelected(position, !wholeNewsMode);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        refreshHomeAds();
        refreshProduct();
    }

    private void scroll(int top, int distance) {
        int tabTop = mNewsTab.getTop() - mNewsTab.getPaddingTop();
        int titleHeight = mHeadBar.getHeight();
        boolean currMode = top >= tabTop;
        if (currMode != wholeNewsMode) {
            //切换模式时，切换tab图标
            MainActivity activity = (MainActivity) getActivity();
            if (activity != null) {
                activity.switchHomeTabIcon(currMode);
            }
            mScrollView.setWholeNewsMode(currMode);
            if (mNewsAdapter != null) {
                //非资讯模式，将资讯中的recyclerview冻住
                mNewsAdapter.setFrozen(!currMode);
            }
        }
        wholeNewsMode = currMode;
        int headPoint = tabTop - titleHeight;
        if (top >= headPoint) {
            int offset = top - headPoint;
            float alpha = offset * 1.5F / titleHeight;
            alpha = alpha > 1 ? 1 : alpha;
            mHeadBar.setTranslationY(-offset * 1.3F);
            mHeadBar.setAlpha(1 - alpha);
        } else {
            mHeadBar.setTranslationY(0);
            mHeadBar.setAlpha(1);
        }
    }

    public void onHomeTabClicked() {
        if (wholeNewsMode) {
            if (mNewsPager != null && mNewsAdapter != null) {
                mNewsAdapter.onRefresh(mNewsPager.getCurrentItem());
            }
        }
    }

    public boolean isWholeNewsMode() {
        return wholeNewsMode;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            refreshHomes();
        }
        if (null != mBanner) {
            mBanner.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (null != mBanner) {
            mBanner.stopAutoPlay();
        }
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCodes(String.valueOf(GTSConst.ZONE_TYPE_SELF)));
    }

    @Override
    public void onRefresh(PullDownScrollView view) {
        refreshHomes();
        if (mNewsPager != null && mNewsAdapter != null) {
            mNewsAdapter.onRefreshAll();
        }
        AppMain.getApp().getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mPullDownScrollView) {
                    mPullDownScrollView.finishRefresh();
                }
            }
        }, 500);
    }

    /**
     * 刷新行情界面数据
     */
    protected void refreshProduct() {
        if (mProductAdapter == null || mProductPager == null) {
            return;
        }
        mProductAdapter.refreshSortData();
        mProductPoint.initPoints(getActivity(), mProductAdapter.getCount(), 0, R.mipmap.a_small_lip, R.mipmap.a_small_lip_p, false);
    }

    /**
     * 刷新首页广告
     */
    public void refreshHomeAds() {
        AdsConfigPresenter.getInstance().loadAds();
        if (null == homePresenter) {
            return;
        }
        //轮播图
        AdsData bannerAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_HOME_BANNER);
        if (bannerAd != null && bannerAd.adPics != null && !bannerAd.adPics.isEmpty()) {
            List<String> imageUrls = new ArrayList<>();
            for (AdsData.PicData data : bannerAd.adPics) {
                imageUrls.add(data.url);
            }
            mBanner.setImages(imageUrls)
                    .setImageLoader(new BannerImageLoader())
                    .setOnBannerListener(new HomeBannerListener(bannerAd.adPics))
                    .setIndicatorGravity(BannerConfig.RIGHT)
                    .start();
        }
        //开户广告
        AdsData openDemoRealAds = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_HOME_OPEN_REAL_DEMO);
        homePresenter.dealOpenAccountAd(openDemoRealAds, tvOpenDemoDesc, tvOpenRealDesc);
        // 新手福利
        AdsData welfareAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_NEW_WELFARE_TOTAL);
        if (mWelfareView != null) {
            mWelfareView.onRefresh(getActivity(), welfareAd);
        }
        //新手指南+关于恒信
        AdsData aboutAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_NEW_GUIDE_AND_ABOUT_US);
        homePresenter.dealNewbieAndAboutUs(getActivity(), aboutAd, ivNewbie, ivAboutUs);
        //首页浮动的
        AdsData floatAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_HOME_FLOAT);
        if (mFloatAdView != null) {
            mFloatAdView.refresh(getActivity(), floatAd, FloatAdverView.INDEX_HOME);
        }
    }

    /**
     * 首页轮播广告点击事件
     */
    private class HomeBannerListener implements OnBannerListener {

        private final List<AdsData.PicData> mPicDatas;

        HomeBannerListener(List<AdsData.PicData> picData) {
            this.mPicDatas = picData;
        }

        @Override
        public void OnBannerClick(int position) {
            if (mPicDatas == null || mPicDatas.size() <= position) {
                return;
            }
            AdsData.PicData picData = this.mPicDatas.get(position);
            if (picData == null || TextUtils.isEmpty(picData.link)) {
                return;
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKBANNER.getValue() + "_" + position, PackStatis.EventCategory.HOME.getValue(), null, null);
            String url = ConfigUtil.getDealStrUrl(picData.link);
            DataItemDetail item = new ConfigSettingDeal().getItemValue(ConfigType.ADS_DETAIL_TAG, picData.title, url);
            item.setBooleanValue(ConfigType.CONFIG_TYPE_TYPE_HASBACK_TAG, true);
            ActivityManager.showWebPageActivity(getActivity(), item, AppMain.getAppString(R.string.btn_back));
        }
    }

    @Override
    public void registerRxBus() {
        Disposable netRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_NETWORK_STATE + "", Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean isNetWork) {
                        if (isNetWork) {
                            refreshHomes();
                            noticeView.setVisibility(View.VISIBLE);
                        } else {
                            noticeView.setVisibility(View.GONE);
                        }
                    }
                });
        bindSubscription(netRegister);

        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {
                    @Override
                    public void accept(@NonNull Bundle bundle) {
                        onSymbolNotify();
                    }
                });
        bindSubscription(quoteAllRegister);

        Disposable quoteListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {
                    @Override
                    public void accept(@NonNull Bundle bundle) {
                        onSymbolNotify();
                    }
                });
        bindSubscription(quoteListRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {
                    @Override
                    public void accept(@NonNull DataItemDetail model) {
                        onSymbolNotify();
                    }
                });
        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {
                    @Override
                    public void accept(@NonNull DataItemDetail model) {
                        if (null != model) {
                            if (null != mProductAdapter && isResumed() && !isHidden()) {
                                mProductAdapter.refreshData(model);
                            }
                        }
                    }
                });
        bindSubscription(quoteTickRegister);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BaseActivity activity = (BaseActivity) getActivity();
            if (null != activity) {
                activity.setTransparentBar(true);
            }
            startCountDownTimer();
            refreshHomes();
            if (null != mBanner) {
                mBanner.startAutoPlay();
            }
        } else {
            if (null != mBanner) {
                mBanner.stopAutoPlay();
            }
        }
    }

    private void refreshHomes() {
        refreshProduct();
    }

    @Override
    public void onSymbolNotify() {
        super.onSymbolNotify();
        refreshProduct();
        onSendQuote();
    }

    @Override
    public void onClick(View v) {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.home_service:
                new ConfigSettingDeal().openQQ(getActivity(), ConfigType.QQ_SOURCE_HOME);
                break;
            case R.id.home_open_account_real:
                ActivityManager.showOpenAccount(getActivity(), ConfigType.ADD_LOGIN_REAL_TAG, getString(R.string.home_open_account_real));
                break;
            case R.id.home_open_account_demo:
                ActivityManager.showOpenAccount(getActivity(), ConfigType.ADD_LOGIN_DEMO_TAG, getString(R.string.home_open_account_demo));
                break;
            default:
                break;
        }
    }

}
